package com.example.floatingpopulation.service.impl;

import com.example.floatingpopulation.utils.VerificationCodeStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

@Service
public class SimpleCodeManager {

	@Autowired
	JavaMailSender mailSender;

	@Autowired
	private VerificationCodeStore verificationCodeStore;

	public void sendMail(String email){
		String code = Double.toString(Math.random()).substring(2,8);
		verificationCodeStore.storeCode(email, code);
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			@Override
			public void prepare(MimeMessage mimeMessage) throws Exception {
				mimeMessage.setRecipient(Message.RecipientType.TO,
						new InternetAddress(email));
				mimeMessage.setFrom(new InternetAddress("1790937482@qq.com"));
				mimeMessage.setText("欢迎使用东莞流动人口统计管理系统，验证码是：" + code);
			}
		};

		try {
			mailSender.send(preparator);
		} catch (MailException ex){
			System.err.println(ex.getMessage());
		}
	}



}
